package com.emm.yixun.website.controller.marketing;
//框架包
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
//变化的引用
import com.emm.yixun.common.model.ReserveArea;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.ReserveAreaDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.marketing.service.ReserveAreaServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.image.WsImageService;
import com.emm.yixun.website.service.marketing.ReserveAreaService;
import com.emm.yixun.website.vo.common.ExtResultVo;




@Controller
@RequestMapping("/marketing/reserveArea/")
public class ReserveAreaController extends BaseController<ReserveArea>{
	
	@Autowired
	private ReserveAreaServiceFacade reserveAreaServiceFacade;
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private WsImageService wsImageService;
	@Autowired
	private ReserveAreaService reserveAreaService;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));		
			return "/marketing/reserveArea/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(ReserveAreaDto dto,String start,String end,String fileUrlArr, String imageType){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"deal:reserveArea:add"))){
        	try {
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        		if(!StringUtils.isEmpty(start)){
        			dto.setReceivableDate(df.parse(start));
        		}
        		if(!StringUtils.isEmpty(end)){
        			dto.setTrusteesDate(df.parse(end));
        		}
        		User user=ShiroUtil.getCurrentUser();
        		Response<Signed> signedResponse=signedServiceFacade.findById(dto.getSignedId());
        		Signed signed =signedResponse.getEntity();
        		Long projectId=signed.getProjectId();
                if(null==projectId){
                    ar.setFailMsg("项目不存在!");
                    return ar;
                }
        		dto.setUserCode(user.getUserCode());
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUserId(user.getId());
				Response<ReserveAreaDto> response=reserveAreaServiceFacade.save(dto);
				if(response.isSuccess()){
					ReserveAreaDto reserveArea = response.getEntity();
					//修改审核状态
					ReserveAreaDto upd = new ReserveAreaDto();
					upd.setId(reserveArea.getId());
					upd.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());//已通过
					reserveAreaServiceFacade.updateByPrimaryKey(upd, true);
					
					//保存流程附件
					if(org.apache.commons.lang3.StringUtils.isNotBlank(fileUrlArr)){
	                     //附件上传功能变更（JHSong）
	                     wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType, response.getEntity().getAccessCode());
	                }
					
					//保存应退款记录
					Response<NeedReceiveRefundDto> res = reserveAreaService.notify(reserveArea);
					if(!res.isSuccess()){
						ar.setFailMsg("应退款记录保存失败");
						logger.debug("reserveArea 应退款记录保存失败");
						return ar;
					}
					
					//实测面积更新房间建筑面积
					Long roomId=signed.getRoomId();
					BigDecimal measuredArea=reserveArea.getMeasuredArea();
					if(null!=measuredArea){
						ProjectRoomDto projectRoomDto=new ProjectRoomDto();
						projectRoomDto.setId(roomId);
						projectRoomDto.setBuildingArea(measuredArea);
						projectRoomServiceFacade.updateByPrimaryKey(projectRoomDto, true);
					}
					ar.setSucceed(response.getEntity());
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:reserveArea:view"))){
        	try {
				Response<ReserveArea> response=reserveAreaServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(ReserveAreaDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:reserveArea:edit"))){
        	try {
        		Response<Integer> response=reserveAreaServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:reserveArea:delete"))){
        	try {
        		Response<Integer> response=reserveAreaServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(ReserveAreaDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:reserveArea:list"))){
        	try {
        		Page<ReserveArea> response=reserveAreaServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<ReserveArea>());
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	@RequestMapping(value = "addReserveArea")
	public ModelAndView addReserveArea(Long sigId,String menu){
		User user = ShiroUtil.getCurrentUser();
		return new ModelAndView("/marketing/reserveArea/add")
		.addObject("sigId", sigId)
		.addObject("userName", user.getUserName())
		.addObject("menu", menu)
		.addObject("permitBtn", getPermissionBtnArray());
	}
	
	@RequestMapping(value = "loadReserveAreaForm")
	public @ResponseBody ExtResultVo loadReserveAreaForm(Long sigId){
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		vo.setData(reserveAreaServiceFacade.reserveAreaFrom(sigId));
		return vo;
	}
	
	@RequestMapping(value = "reserveAreaDetail")
	public ModelAndView reserveAreaDetail(Long id,String processFlag){
		 Response<ReserveArea> response=reserveAreaServiceFacade.findById(id);
        
		return new ModelAndView("/marketing/reserveArea/detail").addObject("id", id).addObject("processFlag", processFlag).addObject("auditStatus", response.getEntity().getAuditStatus()).addObject("procInstId", response.getEntity().getProInsId());
	}
	/**
	* 方法描述 : 加载表单数据
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： ReserveAreaController.java
	* 版本： v1.0
	* 创建时间： 2016年7月13日 下午4:28:19
	* @param id
	* @return ExtResultVo
	 */
	@RequestMapping(value  = "loadReserveAreaDetail")
	public @ResponseBody ExtResultVo loadReserveAreaDetail(Long id){
		ExtResultVo result = new ExtResultVo();
		result.setSuccess(true);
		result.setData(reserveAreaServiceFacade.reserveAreaDetail(id));
		return result;
	}
}
